<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\Vpn\CreateRequest;
use App\Http\Requests\Admin\Vpn\UpdateRequest;
use App\Models\Admin\Level;
use App\Models\Vpn;
use App\Http\Controllers\Controller;

class VpnController extends Controller
{
    public function index()
    {
        $vpns = Vpn::with('level')->get();
        return view('admin.vpn.index', compact('vpns'));
    }

    public function create()
    {
        $levels = Level::all();
        return view('admin.vpn.create', compact('levels'));
    }

    public function store(CreateRequest $request)
    {
        $data = $request->all();
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('avatars', ['disk' => 'public']);
        }
        if (Vpn::create($data)) {
            return redirect()->to(route('admin.vpn'))->with(['status' => '添加成功']);
        }
        return redirect()->to(route('admin.vpn'))->withErrors('系统错误');
    }

    public function update(UpdateRequest $request, $id)
    {
        $data = $request->all();
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('avatars', ['disk' => 'public']);
        }
        $vpn = Vpn::findOrFail($id);
        if ($vpn->update($data)) {
            return redirect()->to(route('admin.vpn'))->with(['status' => '编辑成功']);
        }
        return redirect()->to(route('admin.vpn'))->withErrors('系统错误');
    }

    public function edit($id)
    {
        $levels     = Level::all();
        $vpn        = Vpn::findOrFail($id);
        $vpn->image = '/storage/' . $vpn->image;
        return view('admin.vpn.edit', compact('levels', 'vpn'));
    }

    public function destroy($id)
    {
        Vpn::destroy($id);
        return redirect()->to(route('admin.vpn'))->with(['status' => '删除成功']);
    }
}
